/**
 * banner图片
 */
const AV = require("leanengine");
const BaseService = require("./baseService");
class Service extends BaseService {
  constructor() {
    super("Banner");
  }

  async upload(ctx) {
    const file = ctx.request.files;
    console.log(file.file.name);
    let entry = new AV.Object("Banner");
    try {
      let result = await this.uploadIns(file);
      let url = result.get("url");
      let imgId = result.id;
      let name = file.file.name;
      entry.set("url", url);
      entry.set("name", name);
      // entry.set("imgId", imgId);
      entry.set("status", false);
      result = await entry.save();
      return {
        code: "666",
        msg: "图片上传成功",
        image: {
          url,
          imgId,
          name,
        }
      };
    } catch (error) {
      return this.errInfo(error);
    }
  }

  async delById(ctx) {
    let {
      bannerId
    } = ctx.params;
    let entry = AV.Object.createWithoutData('Banner', bannerId);
    try {
      let result = await entry.destroy();
      return {
        code: '666',
        msg: '删除成功'
      }
    } catch (error) {
      return this.errInfo(error);
    }
  }

  async changStatus(ctx) {
    let {
      bannerId,
      status,
    } = ctx.params;
    let entry = AV.Object.createWithoutData('Banner', bannerId);
    entry.set('status', status);
    try {
      let result = await entry.save();
      return {
        code: '666',
        msg: '状态切换成功'
      }
    } catch (error) {
      return this.errInfo(error);
    }

  }

  async getList(ctx) {
    let query = new AV.Query('Banner');
    try {
      let result = await query.find();
      let imgs = result.map(item => {
        return {
          ...item.attributes,
          bannerId: item.id
        }
      })
      return {
        code: '666',
        msg: 'success',
        imgs
      }
    } catch (error) {
      return this.errInfo(error);
    }
  }
}

module.exports = new Service();
